package com.ruoyi.util;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.domain.Partyclass;
import com.ruoyi.domain.RiverView;
import com.ruoyi.service.IPartyclassService;
import com.ruoyi.service.IRiverViewService;
import com.ruoyi.service.impl.PartyclassServiceImpl;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class AsyncUploadService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IRiverViewService riverViewService;

    @Autowired
    private IPartyclassService partyclassService;

    @Async
    public void asyncUploadVideo(RiverView riverView, byte[] fileBytes, String originalFilename) {
        try {
            String basePath = "videoFiles/";
            String newFileName = generateUniqueFileName(originalFilename);
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + newFileName;

            InputStream inputStream = new ByteArrayInputStream(fileBytes);

            FileInfo fileInfo = fileStorageService.of(inputStream, objectName).setPath(objectName).upload();
            riverView.setVideo(fileInfo.getUrl());

            // 根据 ID 是否存在决定执行 insert 还是 update
            if (riverView.getId() == null || riverViewService.selectRiverViewById(riverView.getId()) == null) {
                // 数据库中无此 ID，执行新增
                riverViewService.insertRiverView(riverView);
            } else {
                // 存在，执行更新
                riverViewService.updateRiverView(riverView);
            }

            System.out.println("【视频上传成功】" + fileInfo.getUrl());
            // 可以考虑添加日志记录或其他通知机制
        } catch (Exception e) {
            System.err.println("【视频上传失败】" + e.getMessage());
            e.printStackTrace();
        }
    }


    @Async
    public void asyncUploadCoverImg(RiverView riverView, byte[] fileBytes, String originalfilename) {
        try {
            String basePath = "cover_imgFiles/";
            String newFileName = generateUniqueFileName(originalfilename);
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + newFileName;

            InputStream inputStream = new ByteArrayInputStream(fileBytes);

            FileInfo fileInfo = fileStorageService.of(inputStream, objectName).setPath(objectName).upload();
            riverView.setCover_img(fileInfo.getUrl());

            if (riverView.getId() == null || riverViewService.selectRiverViewById(riverView.getId()) == null) {
                riverViewService.insertRiverView(riverView);
            } else {
                riverViewService.updateRiverView(riverView);
            }

            System.out.println("【封面图上传成功】" + fileInfo.getUrl());
        } catch (Exception e) {
            System.err.println("【封面图上传失败】" + e.getMessage());
            e.printStackTrace();
        }
    }

    //partyFile视频上传
    @Async
    public void asyncUploadPartyFile(Partyclass partyclass, byte[] fileBytes, String originalFilename) {
        try {
            System.out.println("【开始上传视频】ID: " + partyclass.getId() + ", 文件名: " + originalFilename);
            
            String basePath = "partyFiles/";
            String newFileName = generateUniqueFileName(originalFilename);
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + newFileName;

            InputStream inputStream = new ByteArrayInputStream(fileBytes);

            FileInfo fileInfo = fileStorageService.of(inputStream, objectName).setPath(objectName).upload();
            
            System.out.println("【视频上传完成】URL: " + fileInfo.getUrl());
            
            // 只更新视频文件字段
            Partyclass updatePartyclass = new Partyclass();
            updatePartyclass.setId(partyclass.getId());
            updatePartyclass.setFile(fileInfo.getUrl());
            
            // 执行更新
            int result = partyclassService.updatePartyclass(updatePartyclass);
            
            System.out.println("【视频数据库更新结果】result: " + result + ", ID: " + partyclass.getId() + ", URL: " + fileInfo.getUrl());
            
            if (result > 0) {
                System.out.println("【视频上传成功】" + fileInfo.getUrl());
            } else {
                System.err.println("【视频数据库更新失败】ID: " + partyclass.getId());
            }
        } catch (Exception e) {
            System.err.println("【视频上传失败】" + e.getMessage());
            e.printStackTrace();
            
            // 发生异常时也更新状态，避免前端一直等待
            try {
                Partyclass errorUpdate = new Partyclass();
                errorUpdate.setId(partyclass.getId());
                errorUpdate.setFile("upload_failed");
                partyclassService.updatePartyclass(errorUpdate);
            } catch (Exception ex) {
                System.err.println("【更新错误状态失败】" + ex.getMessage());
            }
        }
    }
    
    //partyFile封面图片上传
    @Async
    public void asyncUploadPartyCoverImg(Partyclass partyclass, byte[] fileBytes, String originalFilename) {
        try {
            System.out.println("【开始上传封面图片】ID: " + partyclass.getId() + ", 文件名: " + originalFilename);
            
            String basePath = "partyCoverFiles/";
            String newFileName = generateUniqueFileName(originalFilename);
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + newFileName;

            InputStream inputStream = new ByteArrayInputStream(fileBytes);

            FileInfo fileInfo = fileStorageService.of(inputStream, objectName).setPath(objectName).upload();
            
            System.out.println("【封面图片上传完成】URL: " + fileInfo.getUrl());
            
            // 只更新封面图片字段
            Partyclass updatePartyclass = new Partyclass();
            updatePartyclass.setId(partyclass.getId());
            updatePartyclass.setCoverImg(fileInfo.getUrl());
            
            // 执行更新
            int result = partyclassService.updatePartyclass(updatePartyclass);
            
            System.out.println("【封面图片数据库更新结果】result: " + result + ", ID: " + partyclass.getId() + ", URL: " + fileInfo.getUrl());
            
            if (result > 0) {
                System.out.println("【封面图片上传成功】" + fileInfo.getUrl());
            } else {
                System.err.println("【封面图片数据库更新失败】ID: " + partyclass.getId());
            }
        } catch (Exception e) {
            System.err.println("【封面图片上传失败】" + e.getMessage());
            e.printStackTrace();
            
            // 发生异常时也更新状态，避免前端一直等待
            try {
                Partyclass errorUpdate = new Partyclass();
                errorUpdate.setId(partyclass.getId());
                errorUpdate.setCoverImg("upload_failed");
                partyclassService.updatePartyclass(errorUpdate);
            } catch (Exception ex) {
                System.err.println("【更新错误状态失败】" + ex.getMessage());
            }
        }
    }


    private String generateUniqueFileName(String originalFilename) {
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID() + ext;
    }
}
